<?php
class Price_rule_model extends CI_Model{
	function __construct(){
		parent::__construct();
	}

	public function get_discount($percentage){
		$this->db->where('price_rule_percent <=', $percentage);
		$this->db->order_by("price_rule_percent", "desc");
		$query = $this->db->get('price_rule');
		if ($query->num_rows() > 0)
		{
			return $query->row()->price_rule_discount;
		}
		return 0;
	}

	public function get_price_rule_by_discount($percentage){
		$this->db->where('price_rule_percent <=', $percentage);
		$this->db->order_by("price_rule_percent", "desc");
		$query = $this->db->get('price_rule');
		if ($query->num_rows() > 0)
		{
			return $query->row();
		}
		return 0;
	}

	public function get_all(){
		$query = $this->db->get('price_rule');
		return $query->result();
	}

	public function add($percent, $discount){

		$data = array(
				'price_rule_percent' => $percent ,
				'price_rule_discount' => $discount
		);
		if ($this->db->insert('price_rule', $data)){
			$this->__update();
			return $this->db->insert_id();
		}else
			return -1;
	}

	public function update($price_rule_id, $percent, $discount){
		$data = array(
				'price_rule_percent' => $percent,
				'price_rule_discount' => $discount
		);
		$this->db->where('price_rule_id', $price_rule_id);
		if ($this->db->update('price_rule', $data)){
			$this->__update();
			return true;
		}else
			return false;
	}

	public function get_id($price_rule_percent){

		$query = $this->db->where('price_rule_percent',$price_rule_percent)->get('price_rule');
		if ($query->num_rows() > 0)
		{
			$row = $query->row();
			return $row->price_rule_id;
		}else
			return -1;
	}

	public function delete($id){

		$this->db->where('price_rule_id', $id);
		if ($this->db->delete('price_rule')){
			$this->__update();
			return true;
		}else
			return false;
	}

	private function __update(){
		$this->db->query("CALL update_discount()");
	}

	public function get_price_rule_by_id($id){
		$query = $this->db->where('price_rule_id', $id)->get('price_rule');

		if ($query->num_rows() > 0)
		{
			return $query->row();
		}else
			return null;
	}



}